﻿using Architecture.Logging.Agent.Configuration;
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Session;
using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Results;

namespace Architecture.Logging.Agent.Services.Admin
{
    public class SourcesController : ApiController
    {
        // GET api/values 
        public IEnumerable<TraceProvider> Get()
        {

            return LoggingConfiguration.Current.GetProviders();


            //return new string[] { "value1", "value2" };
        }

        [Route("api/sources/{id}", Name = "GetProviderById")]
        [HttpGet()]
        public IHttpActionResult GetById(Guid id)
        {
            var item = LoggingConfiguration.Current.FindById(id);
            if (item == null)
            {
                return NotFound();
            }
            return Ok(item);
        }

        [HttpPut()]
        public IHttpActionResult Update(TraceProvider provider)
        {
            var item = LoggingConfiguration.Current.FindById(provider.Id);
            if (item == null)
            {
                return NotFound();
            }

            if (item.Enabled != provider.Enabled)
            {

                using (var session = new TraceEventSession("ArchitectureResearch"))
                {

                    session.StopOnDispose = true;
                    using (var source = new ETWTraceEventSource(session.SessionName, TraceEventSourceType.Session))
                    {
                        Context.Current.Source = source;
                        var registeredParser = new RegisteredTraceEventParser(source);
                        registeredParser.All += delegate (TraceEvent data)
                        {
                            //var log = ETWIISLogParser.Current.CreateFromTraceEvent(data);
                            //using (var ctx = new LoggingServiceContext())
                            //{
                            //    ctx.IISLogs.Add(log);
                            //    ctx.SaveChanges();
                            //}
                            var taskName = data.TaskName;
                            System.Diagnostics.Debug.WriteLine(taskName);
                            System.Console.WriteLine(String.Format("{0} - {1}", taskName, data.FormattedMessage));
                        };

                        if (item.Enabled)
                        {
                            //Enable IIS Provider Logging Microsoft-Windows-IIS-Logging
                            session.EnableProvider(Guid.Parse("7E8AD27F-B271-4EA2-A783-A47BDE29143B"), TraceEventLevel.Always);
                        }
                        else
                        {
                            session.DisableProvider(Guid.Parse("7E8AD27F-B271-4EA2-A783-A47BDE29143B"));
                        }
                        source.Process();
                    }
                }
            }
            item.Enabled = provider.Enabled;

            return Ok(item);
        }

        [HttpPost()]
        public IHttpActionResult AddProvider(TraceProvider provider)
        {
            var item = LoggingConfiguration.Current.FindById(provider.Id);
            if (item != null)
            {
                return new ConflictResult(this);
            }

            LoggingConfiguration.Current.AddProvider(provider);

            return Ok(provider);
        }



    }
}
